package com.cy.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository//此注解一般用于描述数据访问对象的具体实现类
public class NoticeJdbcDaoImpl implements NoticeJdbcDao{
    @Autowired
    private DataSource dataSource;
    @Override
    public void insertNotice(String sql,Object[] values) throws SQLException{
        Connection conn = dataSource.getConnection();

        PreparedStatement stmt = conn.prepareStatement(sql);

        for (int i =0;i<values.length;i++){
            stmt.setObject(i+1,values[i]);
        }

//        stmt.setString(1,"开学通知");
//        stmt.setString(2,"2021年3月18号  开学");
//        stmt.setString(3,"1");
//        stmt.setString(4,"0");
//        stmt.setTimestamp(5,new Timestamp(System.currentTimeMillis()));
//        stmt.setString(6,"jason");
//        stmt.setTimestamp(7,new Timestamp(System.currentTimeMillis()));
//        stmt.setString(8,"tony");
        stmt.execute();
        stmt.close();
        conn.close();
    }

    @Override
    public List<Map<String, Object>> selectNotices(String sql,Object values[]) throws SQLException {
        Connection conn = dataSource.getConnection();
    //    String sql = "select id,title,content,status,type,createdTime" + " from sys_notices where id>=?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        for (int i=0;i<values.length;i++){
            pstmt.setObject(i+1, values[i]);
        }

        boolean flag = pstmt.execute();
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList<>();
        if (flag) {
            rs = pstmt.getResultSet();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                //getColumnCount()获取列的数量
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    //getColumnLabel(i)获取当前字段名
                    map.put(rsmd.getColumnLabel(i), rs.getObject(rsmd.getColumnLabel(i)));
                    System.out.println(rsmd.getColumnLabel(i) + "             " + rsmd.getColumnName(i));
                }
                System.out.println(map);
                list.add(map);
            }
        }

        rs.close();
        pstmt.close();
        conn.close();
        return list;
    }

    @Override
    public void update(String sql, Object[] values) throws SQLException {
        Connection conn = dataSource.getConnection();
        PreparedStatement statement = conn.prepareStatement(sql);

        for (int i = 0; i < values.length; i++) {
            statement.setObject(i+1,values[i]);
        }

        statement.execute();
        conn.close();
        statement.close();

    }


}
